package com.my.xq.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.my.wechat.controller.WxTemplateMesController;
import com.my.xq.domain.RenWuQueryParam;
import com.my.xq.domain.entity.Court;
import com.my.xq.domain.entity.Doorplate;
import com.my.xq.domain.entity.RenWu;
import com.my.xq.domain.entity.RenWuCreate;
import com.my.xq.domain.entity.RenWuDefine;
import com.my.xq.repository.CourtRepository;
import com.my.xq.repository.DoorplateRepository;
import com.my.xq.repository.ProprietorRepository;
import com.my.xq.repository.RenWuCreateRepository;
import com.my.xq.repository.RenWuRepository;
import com.sskj.common.util.CalendarUtil;
import com.sskj.core.annotation.ControllerLogExeTime;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/rw")
public class RenWuServiceImpl {

	@Autowired
	RenWuRepository rwRepository;

	@Autowired
	RenWuCreateRepository rwCreateRepository;

	@Autowired
	CourtRepository courtRepository;

	@Autowired
	DoorplateRepository doorplateRepository;

	@Autowired
	ProprietorRepository proprietorRepository;

	@Autowired
	private WxMpService wxService;

	@Value(value = "${wechat.mp.voteTempleteCode}")
	private String voteTempleteCode;

	@Value(value = "${sskj.conf.webDomain}")
	private String webDomain;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	public void addRenWuInfo(RenWu p) {
		rwRepository.save(p);
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "查询一条任务记录", log = false)
	@RequestMapping("/findOne")
	public RenWu findOne(String id, HttpServletRequest request) {
		RenWu r = rwRepository.get(id);
		return r;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping("/findRenWuActive")
	@ApiOperation(value = "获取绑定小区正在进行的任务", notes = "获取绑定小区正在进行的任务", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "courtId", value = "courtId", paramType = "form", dataType = "string") })
	public RenWu loadDoorBind(@ApiIgnore RenWuQueryParam p) {
		RenWu r = rwRepository.findRenWuActive(p.getCourtId());
		return r;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping("/activeRenwu")
	@ApiOperation(value = "获取绑定小区正在进行的任务", notes = "获取绑定小区正在进行的任务", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "courtId", value = "courtId", paramType = "form", dataType = "string") })
	public Object activeRenwu(@ApiIgnore String courtId) {
		RenWu r = rwRepository.findRenWuActive(courtId);
		return r == null ? false : r;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "获取绑定小区正在进行的任务列表", log = false)
	@RequestMapping("/loadCourtActiveTask")
	public List<RenWuCreate> loadCourtActiveTask(Doorplate d) {

		// 首先获取现在正在进行中的任务
		RenWu renwu = rwRepository.findRenWuActive(d.getCourtId());
		List<RenWuCreate> rwcList = new ArrayList<RenWuCreate>();
		if (renwu != null) {
			// 根据业主id获取指定小区所有的门牌号
			List<Doorplate> list = doorplateRepository.LoadDoorPriproCast(d.getCourtId(), d.getProprietorId());

			for (int i = 0; i < list.size(); i++) {
				// 然后根据这个任务Code分情况获取数据
				Doorplate door = list.get(i);
				if (renwu.getCode().equals(RenWuDefine.CAST01.toString())) { // 如果是竞选单元长
					RenWuCreate rc = rwCreateRepository.findRenWuByUnit(door.getCourtId(), renwu.getCode(),
							door.getBuilding(), door.getUnit());
					if (null != rc) {
						rwcList.add(rc);
					}
				} else if (renwu.getCode().equals(RenWuDefine.CAST02.toString())) { // 如果是竞选楼栋长
					RenWuCreate rc = rwCreateRepository.findRenWuBybuilding(door.getCourtId(), renwu.getCode(),
							door.getBuilding());
					if (null != rc) {
						rwcList.add(rc);
					}
				} else if (renwu.getCode().equals(RenWuDefine.CAST03.toString())
						|| renwu.getCode().equals(RenWuDefine.CAST04.toString())) {
					RenWuCreate rc = rwCreateRepository.findRenWuByCode(door.getCourtId(), renwu.getCode());
					if (null != rc) {
						rwcList.add(rc);
					}
				} else {
					logger.error("获取到的任务Code不对");
				}
			}
		}
		HashSet<RenWuCreate> h = new HashSet<RenWuCreate>(rwcList);
		rwcList.clear();
		rwcList.addAll(h);
		return rwcList;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "获取绑定小区正在进行的任务列表", log = false)
	@RequestMapping("/activeReWu")
	public List<RenWuCreate> getActiveReWuByCourtId(String courtId, String proprietorId) {

		List<RenWuCreate> rwcList = new ArrayList<RenWuCreate>();
		// 首先获取现在正在进行中的任务
		RenWu renwu = rwRepository.findRenWuActive(courtId);
		if (renwu != null) {
			// rwcList = rwCreateRepository.findRenWuLsByCourt(courtId, proprietorId, renwu.getCode());
		}
		return rwcList;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@ControllerLogExeTime(description = "获取绑定小区正指定的任务列表", log = false)
	@RequestMapping("/activeReWu/code")
	public List<RenWuCreate> getActiveReWuByRwCode(String courtId, String proprietorId, String rwCode) {
		if ("CAST01".equals(rwCode)) {
			return rwCreateRepository.findRenWuCAST01LsByCourt(courtId, proprietorId);
		} else if ("CAST02".equals(rwCode)) {
			return rwCreateRepository.findRenWuCAST02LsByCourt(courtId, proprietorId);
		} else if ("CAST03".equals(rwCode)) {
			return rwCreateRepository.findRenWuCAST03LsByCourt(courtId);
		} else if ("CAST04".equals(rwCode)) {
			return rwCreateRepository.findRenWuCAST04LsByCourt(courtId);
		} else {
			return new ArrayList<RenWuCreate>();
		}
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping("/findBuddySignUp")
	@ApiOperation(value = "根据任务ID查询已经报名过的人", notes = "根据任务ID查询已经报名过的人", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "courtId", value = "courtId", paramType = "form", dataType = "string") })
	public List<Doorplate> findBuddySignUp(RenWuCreate rc) {
		List<Doorplate> list = null;
		String rwCode = rc.getRwCode();
		if (rwCode.equals(RenWuDefine.CAST01.toString())) { // 单元长投票
			list = doorplateRepository.findUnitSignUp(rc.getCourtId(), rc.getUnit(), rc.getBuilding());
		}
		if (rwCode.equals(RenWuDefine.CAST02.toString())) { // 楼栋长投票
			list = doorplateRepository.findBuildingSignUp(rc.getCourtId(), rc.getBuilding());
		}
		if (rwCode.equals(RenWuDefine.CAST03.toString())) { // 楼栋长互投，竞选委员
			list = doorplateRepository.findBuildingRole("楼栋长", rc.getCourtId());
		}
		if (rwCode.equals(RenWuDefine.CAST04.toString())) { // 委员互投，竞选主任
			list = doorplateRepository.findBuildingRole("委员", rc.getCourtId());
		}
		if (!list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {
				Doorplate dp = list.get(i);
				String proprietorId = dp.getProprietorId();
				if (null != proprietorId) {
					dp.setProprietorName(proprietorRepository.get(proprietorId).getName());
				}
			}
		}
		return list;
	}

	/**
	 * 根据小区ID查询业委会选举任务状态
	 * 
	 * @param courtId
	 * @return 任务状态列表
	 */
	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping("/status")
	@ApiOperation(value = "根据小区ID查询业委会选举任务状态", notes = "根据小区ID查询业委会选举任务状态", httpMethod = "GET")
	List<RenWu> rwStatus(String courtId) {
		List<RenWu> result = rwRepository.findRenWuByCourtId(courtId);
		return result;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/open", method = { RequestMethod.GET })
	@ApiImplicitParams({
		@ApiImplicitParam(name = "courtId", value = "courtId", paramType = "form", dataType = "string"),
		@ApiImplicitParam(name = "rwCode", value = "rwCode", paramType = "form", dataType = "string"),
		})
	public boolean openRenWu(String courtId, String rwCode) {
		List<RenWu> rw = rwRepository.findRenWuLsByCourt(courtId, rwCode);
		if (null != rw && !rw.isEmpty()) {
			RenWu r = rw.get(0);
			if (!r.isActive()) {
				r.setActive(true);
				Date now = new Date();
				r.setStartTime(now);
				Calendar ca = Calendar.getInstance();
				ca.add(Calendar.DATE, 7); // 默认期限为3天
				r.setEndTime(ca.getTime());
				rwRepository.save(r);
				renWuCreateUnit(courtId);
				// 给小区所有人发送竞选单元长的模板消息
				List<String> list = doorplateRepository.findIsBingOpenId(courtId);
				if (!list.isEmpty()) {
					// 发送模板消息
					WxTemplateMesController wmc = new WxTemplateMesController();
					for (int i = 0; i < list.size(); i++) {
						try {
							Court c = courtRepository.get(courtId);
							wxService.getTemplateMsgService()
									.sendTemplateMsg(wmc.getTemplate(list.get(i), c.getName(), "报名入口",
											CalendarUtil.getDate(), "http://" + webDomain + "#/home/my",
											voteTempleteCode));
						} catch (WxErrorException e) {
							logger.error("发送模板消息失败");
							e.printStackTrace();
						}
					}
				}
				return true;
			}
		}
		return false;
	}

	private void renWuCreateUnit(String courtid) {

		List<Doorplate> ds = doorplateRepository.LoadBindDoorCoundByCourt(courtid);

		Map<String, Set<String>> rwMap = new HashMap<String, Set<String>>();
		for (Doorplate d : ds) {
			if (StringUtils.isNotEmpty(d.getBuilding()) && StringUtils.isNotEmpty(d.getUnit())) {
				rwMap.put(d.getBuilding(), new HashSet());
			}
		}

		for (Doorplate d : ds) {
			rwMap.get(d.getBuilding()).add(d.getUnit());
		}
		Integer num = 0;
		if (num == rwCreateRepository.findCastCount("CAST03", courtid)) {
			RenWuCreate r = new RenWuCreate();
			r.setRwCode("CAST03");
			r.setRwName("委员");
			r.setActive(false);
			r.setCourtId(courtid);
			rwCreateRepository.save(r);
		}

		if (num == rwCreateRepository.findCastCount("CAST04", courtid)) {
			RenWuCreate r = new RenWuCreate();
			r.setRwCode("CAST04");
			r.setRwName("主任");
			r.setActive(false);
			r.setCourtId(courtid);
			rwCreateRepository.save(r);
		}

		Iterator<Map.Entry<String, Set<String>>> entries = rwMap.entrySet().iterator();
		while (entries.hasNext()) {

			Map.Entry<String, Set<String>> entry = entries.next();

			System.out.println("Key 楼栋= " + entry.getKey() + ", Value单元 = " + entry.getValue());
			if (num == rwCreateRepository.findCastCount("CAST02", courtid, entry.getKey())) {
				RenWuCreate r = new RenWuCreate();
				r.setRwCode("CAST02");
				r.setRwName("楼栋长");
				r.setActive(false);
				r.setCourtId(courtid);
				r.setBuilding(entry.getKey());
				rwCreateRepository.save(r);
			}

			for (String content : entry.getValue()) {
				System.out.println("Key 楼栋= " + entry.getKey() + ", Value单元 = " + content);
				if (num == rwCreateRepository.findCastCount("CAST01", courtid, entry.getKey(), content)) {
					RenWuCreate r = new RenWuCreate();
					r.setRwCode("CAST01");
					r.setRwName("单元长");
					r.setActive(true);
					r.setCourtId(courtid);
					r.setBuilding(entry.getKey());
					r.setUnit(content);
					rwCreateRepository.save(r);
				}
			}
		}
	}
}
